package com.yuqing.sentimentapp.yqlist.activity;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linkface.baselibrary.utils.DensityUtil;
import com.linkface.baselibrary.utils.StatusBarUtil;
import com.linkface.common.adaper.CommonViewHolder;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.yuqing.sentimentapp.Constants;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.event.CommonEvent;
import com.yuqing.sentimentapp.event.IssuedEvent;
import com.yuqing.sentimentapp.home.acitivity.ImagePreviewActivity;
import com.yuqing.sentimentapp.home.adapter.YQDetailCommentAdapter;
import com.yuqing.sentimentapp.home.bean.CommentItem;
import com.yuqing.sentimentapp.home.bean.ReplyBean;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.utils.DisplayUtil;
import com.yuqing.sentimentapp.utils.GlideUtil;
import com.yuqing.sentimentapp.utils.KeyBoardUtils;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.widget.DivItemDecoration;
import com.yuqing.sentimentapp.widget.MyNineGridLayout;
import com.yuqing.sentimentapp.widget.jzvideo.Jzvd;
import com.yuqing.sentimentapp.widget.jzvideo.JzvdStd;
import com.yuqing.sentimentapp.yqlist.IssuedHelper;
import com.yuqing.sentimentapp.yqlist.bean.YqDetailResultBean;
import com.yuqing.sentimentapp.yqlist.bean.YqReplyResultBean;
import com.yuqing.sentimentapp.yqlist.presenter.YqDetailPresenter;
import com.yuqing.sentimentapp.yqlist.presenter.impl.YqDetailPresenterImpl;
import com.yuqing.sentimentapp.yqlist.view.YqDetailView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import wseemann.media.FFmpegMediaMetadataRetriever;

/**
 * Created by ShenHe on 2019/3/25.
 */

public class YuQingDetailActivity extends BaseActivity implements YqDetailView<YqDetailResultBean>{
    MyNineGridLayout mNineTestlayout;
    @BindView(R.id.recyclerView)
    SuperRecyclerView recyclerView;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_report)
    TextView mTvReport;
    @BindView(R.id.tv_report_again)
    TextView mTvReportAgain;
    @BindView(R.id.tv_issued)
    TextView mTvIssued;
    TextView mTvTitle;
    TextView mTvSource;
    TextView mTvDate;
    TextView mTvIsSensitive;
    TextView mTvContent;
    View mViewLine;
    @BindView(R.id.editTextBodyLl)
    RelativeLayout mEditTextBodyLl;
    @BindView(R.id.et_reply)
    EditText mEtReply;
    @BindView(R.id.btn_send)
    Button mBtnSend;
    private LinearLayoutManager layoutManager;
    private YQDetailCommentAdapter adapter;
    private YqDetailPresenter mPresenter;
    private String articleId;
    private YqDetailResultBean yqDetailResultBean;
    private List<ReplyBean> replysBeanList = new ArrayList<>();
    private CommonViewHolder.onItemCommonClickListener replyClickListener;
    private String replyContent;
    private int replyPos;
    private int currentKeyboardH;
    private int screenHeight;
    private int editTextBodyHeight;
    private View mLayoutHeader;
    private int position;
    private String deptLevel;
    private JzvdStd mVideoplayer;
    private TextView mTvSourceLink;
    private FrameLayout mLayoutVideo;

    public static void start(Context context, String articleId, int position) {
        Intent starter = new Intent(context, YuQingDetailActivity.class);
        starter.putExtra("articleId", articleId);
        starter.putExtra("position", position);
        context.startActivity(starter);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_yuqing_detail;
    }

    @Override
    public void initPresenter() {
        mPresenter = new YqDetailPresenterImpl(this);
    }

    @Override
    public void initView() {
        initIntent();
        initHeaderView();
        initNineGridLayout();
        initListener();
        initRecyclerView();
        setViewTreeObserver();
        initData();
    }

    private void initHeaderView() {
        mLayoutHeader = LayoutInflater.from(this).inflate(R.layout.layout_yuqing_detail_header, null);
        mTvTitle = mLayoutHeader.findViewById(R.id.tv_title);
        mTvSource = mLayoutHeader.findViewById(R.id.tv_source);
        mTvDate = mLayoutHeader.findViewById(R.id.tv_date);
        mTvIsSensitive = mLayoutHeader.findViewById(R.id.tv_isSensitive);
        mTvContent = mLayoutHeader.findViewById(R.id.tv_content);
        mTvSourceLink = mLayoutHeader.findViewById(R.id.tv_source_link);
        mTvSourceLink.setOnClickListener(v -> {
            if (yqDetailResultBean == null) {
                return;
            }
            YqDetailResultBean.DataBean data = yqDetailResultBean.getData();
            if (data == null) return;
            YqDetailResultBean.DataBean.ArticleBean article = data.getArticle();
            if (article == null) {
                return;
            }
            String url = article.getUrl();
            if (!TextUtils.isEmpty(url)) {
                //跳转到默认浏览器
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        mNineTestlayout = mLayoutHeader.findViewById(R.id.nineTestlayout);
        mLayoutVideo = mLayoutHeader.findViewById(R.id.layout_video);
        mVideoplayer = mLayoutHeader.findViewById(R.id.videoplayer);
        mViewLine = mLayoutHeader.findViewById(R.id.view_line);

        LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();
        if (user != null && user.getDeptVo() != null) {
            deptLevel = user.getDeptVo().getDeptLevel();
        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            articleId = intent.getStringExtra("articleId");
            position = intent.getIntExtra("position", -1);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        EventBus.getDefault().register(this);
        replyClickListener = new CommonViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                if(mEditTextBodyLl.getVisibility() == View.GONE){
                    updateEditTextBodyVisible(View.VISIBLE, position);
                }
            }

            @Override
            public void onItemLongClickListener(int position) {

            }
        };

        mEditTextBodyLl.setOnClickListener((v) -> {
            if(mEditTextBodyLl.getVisibility() == View.VISIBLE){
                updateEditTextBodyVisible(View.GONE, -1);
            }
        });
    }

    private void initRecyclerView() {
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DivItemDecoration(2, true));
        recyclerView.getMoreProgressView().getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;

        adapter = new YQDetailCommentAdapter(this, replysBeanList, replyClickListener);
        ViewGroup parent = (ViewGroup) this.mLayoutHeader.getParent();
        if (parent != null) {
            parent.removeView(this.mLayoutHeader);
        }
        adapter.setHeaderView(this.mLayoutHeader);
        recyclerView.setAdapter(adapter);
    }

    private void initNineGridLayout() {
        mNineTestlayout.setListener((itemPosition, position, url, urlList, imageView) -> {
            Intent intent = new Intent(YuQingDetailActivity.this, ImagePreviewActivity.class);
            intent.putStringArrayListExtra("imageList", (ArrayList<String>) urlList);
            intent.putExtra(Constants.START_IAMGE_POSITION, position);
            ActivityOptions compat = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                compat = ActivityOptions.makeSceneTransitionAnimation(YuQingDetailActivity.this, imageView, imageView.getTransitionName());
                startActivity(intent, compat.toBundle());
            } else {
                startActivity(intent);
            }
        });
        mNineTestlayout.setItemPosition(1);
        mNineTestlayout.setIsShowAll(false); //当传入的图片数超过9张时，是否全部显示
        mNineTestlayout.setSpacing(10); //动态设置图片之间的间隔
    }

    private void setViewTreeObserver() {
        final ViewTreeObserver swipeRefreshLayoutVTO = mEditTextBodyLl.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                mEditTextBodyLl.getWindowVisibleDisplayFrame(r);
                int statusBarH = StatusBarUtil.getStatusBarHeight(YuQingDetailActivity.this);//状态栏高度
                int screenH = mEditTextBodyLl.getRootView().getHeight();
                if(r.top != statusBarH ){
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
                Log.d("RecommendFragment", "screenH＝ "+ screenH +" &keyboardH = " + keyboardH + " &r.bottom=" + r.bottom + " &top=" + r.top + " &statusBarH=" + statusBarH);

                if(keyboardH == currentKeyboardH){//有变化时才处理，否则会陷入死循环
                    return;
                }

                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = mEtReply.getHeight() + DensityUtil.dip2px(YuQingDetailActivity.this, 16);

                if(keyboardH < 150){//说明是隐藏键盘的情况
                    updateEditTextBodyVisible(View.GONE, -1);
                    return;
                }
//                //偏移listview
//                if(layoutManager!=null && commentConfig != null){
//                    layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE, getListviewOffset(commentConfig));
//                }
            }
        });
    }

    public void updateEditTextBodyVisible(int visibility, int position) {
        mEditTextBodyLl.setVisibility(visibility);

        if(View.VISIBLE==visibility){
            mEtReply.requestFocus();
            //弹出键盘
            KeyBoardUtils.showSoftInput(mEtReply.getContext(), mEtReply);

            //回复
            mBtnSend.setOnClickListener(v -> {
                replyContent = mEtReply.getText().toString();
                replyPos = position - 1;//因为有header，所以item的postion减1
                if (TextUtils.isEmpty(replyContent)) {
                    ToastUtil.showShort("回复内容不能为空");
                    return;
                }
                mPresenter.replyRequest(replysBeanList.get(replyPos).getId(), mEtReply.getText().toString(), replyPos);
                //隐藏回复
                if(mEditTextBodyLl.getVisibility() == View.VISIBLE){
                    updateEditTextBodyVisible(View.GONE, -1);
                }
            });
        }else if(View.GONE==visibility){
            //隐藏键盘
            KeyBoardUtils.hideSoftInput(mEtReply.getContext(), mEtReply);
        }
    }



    private void initData() {
        LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();
        if (user == null) return;
        LoginResultBean.DataBean.UserBean.DeptVoBean deptVo = user.getDeptVo();
        if (deptVo == null) return;
        mPresenter.loadYqDetailData(articleId, deptVo.getDeptCode());
    }

    @OnClick({R.id.iv_back, R.id.tv_report, R.id.tv_report_again, R.id.tv_issued})
    public void onClick(View view) {
        switch (view.getId()) {
            default:
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_report:
                if (yqDetailResultBean == null) {
                    return;
                }
                LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();
                String deptLevel = "";
                if (user != null && user.getDeptVo() != null) {
                    deptLevel = user.getDeptVo().getDeptLevel();
                    /**
                     * 总队身份，并且subReplyId不为空，显示上报，但需要把内容引用过去
                     * state=0为上报， state=1为重报
                     * replyId不为空，则去请求接口，拉取数据
                     */
                    if (!TextUtils.isEmpty(deptLevel) && TextUtils.equals(deptLevel, "1")) {
                        YQReportActivity.start(this, yqDetailResultBean.getData().getArticle().getBdArticleId(),
                                yqDetailResultBean.getData().getArticle().getTitle(),
                                yqDetailResultBean.getData().getArticle().getUrl(),
                                yqDetailResultBean.getData().getArticle().getContent(), yqDetailResultBean.getData().getArticle().getSubReplyId(), position, 0);
                        return;
                    }
                }
                YQReportActivity.start(this, yqDetailResultBean.getData().getArticle().getBdArticleId(),
                        yqDetailResultBean.getData().getArticle().getTitle(),
                        yqDetailResultBean.getData().getArticle().getUrl(),
                        yqDetailResultBean.getData().getArticle().getContent(), position, 0);
                break;
            case R.id.tv_report_again:
                if (yqDetailResultBean == null) {
                    return;
                }
                YQReportActivity.start(this, yqDetailResultBean.getData().getArticle().getBdArticleId(),
                        yqDetailResultBean.getData().getArticle().getTitle(),
                        yqDetailResultBean.getData().getArticle().getUrl(),
                        yqDetailResultBean.getData().getArticle().getContent(), yqDetailResultBean.getData().getArticle().getReplyId(), position, 1);
                break;
            case R.id.tv_issued:
                IssuedHelper.getInstance(this).getIssuedPresenter().loadIssuedPrepareRequest(articleId, "", position);
                break;
        }
    }

    @Override
    public void onSuccess(YqDetailResultBean data) {
        if (data == null) {
            return;
        }
        yqDetailResultBean = data;
        if (yqDetailResultBean.getData() == null) return;
        YqDetailResultBean.DataBean dataData = yqDetailResultBean.getData();
        List<ReplyBean> replys = dataData.getReplys();
        YqDetailResultBean.DataBean.ArticleBean article = dataData.getArticle();
        updateArticleView(article);
        if (article != null && article.isVideo()) {
            mLayoutVideo.setVisibility(View.VISIBLE);
            mNineTestlayout.setVisibility(View.GONE);
            mVideoplayer.setUp(article.getVideoUrl(), article.getTitle(), Jzvd.SCREEN_NORMAL);
            if (TextUtils.isEmpty(article.getVideoThumb())) {
                FFmpegMediaMetadataRetriever fmmr = new FFmpegMediaMetadataRetriever();
                try {
                    fmmr.setDataSource(article.getVideoUrl());
                    Bitmap bitmap = fmmr.getFrameAtTime();
                    if (bitmap != null) {
                        Bitmap b2 = fmmr
                                .getFrameAtTime(
                                        4000000,
                                        FFmpegMediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                        if (b2 != null) {
                            bitmap = b2;
                        }
                        if (bitmap.getWidth() > 640) {// 如果图片宽度规格超过640px,则进行压缩
                            bitmap = ThumbnailUtils.extractThumbnail(bitmap,
                                    DisplayUtil.getScreenWidth(mContext) - DensityUtil.dip2px(mContext, 40), DensityUtil.dip2px(mContext, 200),
                                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
                        }
                        mVideoplayer.thumbImageView.setImageBitmap(bitmap);
                    }
                } catch (IllegalArgumentException ex) {
                    ex.printStackTrace();
                } finally {
                    fmmr.release();
                }
            } else {
                GlideUtil.getImageWithErrorLoadingImg(mContext, article.getVideoThumb(), mVideoplayer.thumbImageView, R.drawable.ic_default_big, R.drawable.ic_default_big);
            }
        } else {
            mLayoutVideo.setVisibility(View.GONE);
            mNineTestlayout.setVisibility(View.VISIBLE);
            mNineTestlayout.setUrlList(dataData.getImages());
        }
        if (replys == null || replys.size() == 0) {
            mViewLine.setVisibility(View.GONE);
        }
        updateCommentView(replys);
    }

    private void updateCommentView(List<ReplyBean> replysBeans) {
        replysBeanList.clear();
        replysBeanList.addAll(replysBeans);
        adapter.notifyDataSetChanged();
    }

    private void updateArticleView(YqDetailResultBean.DataBean.ArticleBean data) {
        if (data == null) {
            return;
        }
        mTvTitle.setText(data.getTitle());
        mTvSource.setText(data.getSource());
        mTvDate.setText(data.getCreatedAt());
        if (TextUtils.isEmpty(data.getSentiment())) {
            mTvIsSensitive.setVisibility(View.GONE);
        } else {
            mTvIsSensitive.setVisibility(View.VISIBLE);
            switch (data.getSentiment()) {
                case "A":
                    mTvIsSensitive.setText("正面");
                    break;
                case "B":
                    mTvIsSensitive.setText("负面");
                case "C":
                    mTvIsSensitive.setText("敏感");
                    break;
            }
        }
        mTvContent.setText(data.getContent());

        // 部局身份 上报隐藏
        if (!TextUtils.isEmpty(deptLevel) && TextUtils.equals("0", deptLevel)) {//部门级别：0部级1省级2市级
            mTvReport.setVisibility(View.GONE);
            mTvReportAgain.setVisibility(View.GONE);
        } else {
            if (TextUtils.isEmpty(data.getReplyId())) {//上报
                showReportView();
            } else {//重报
                showReportAgainView();
            }
        }

        // 支队隐藏下发，已下发后隐藏下发
        mTvIssued.setVisibility(!TextUtils.isEmpty(data.getPubId()) || (!TextUtils.isEmpty(deptLevel) && TextUtils.equals("2", deptLevel)) ? View.GONE : View.VISIBLE);
    }

    private void showReportAgainView() {
        mTvReportAgain.setVisibility(View.VISIBLE);
        mTvReport.setVisibility(View.GONE);
    }

    private void showReportView() {
        mTvReport.setVisibility(View.VISIBLE);
        mTvReportAgain.setVisibility(View.GONE);
    }

    /**
     * 上报事件注册
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final CommonEvent event) {
        if (event.getMsg() == -1) {// 上报
            initData();
        }
    }

    /**
     * 下发事件注册
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final IssuedEvent event) {
        mTvIssued.setVisibility(View.GONE);
    }

    @Override
    public void onFailure(String message) {
        ToastUtil.showShort(message);
    }

    @Override
    public void replySuccess(YqReplyResultBean baseBean, int position) {
        ToastUtil.showShort("回复成功");
        //清空输入框内容
        mEtReply.setText("");

        if (baseBean == null) return;
        //更新回复列表
        YqReplyResultBean.DataBean replyBean = baseBean.getData();
        if (replyBean == null) return;
        updateReplysView(replyBean, position);
        EventBus.getDefault().post(new CommonEvent(1, replyBean.getSubStatus(), this.position));
    }

    private void updateReplysView(YqReplyResultBean.DataBean replyBean, int position) {
        CommentItem commentItem = new CommentItem();
        commentItem.setId(replyBean.getId());
        commentItem.setReplyId(replyBean.getReplyId());
        commentItem.setContent(replyBean.getContent());
        commentItem.setDeptCode(replyBean.getDeptCode());
        commentItem.setDeptName(replyBean.getDeptName());
        commentItem.setCreateAt(replyBean.getCreateAt());
        commentItem.setUsername(SharePrefrenceHelper.getUser().getUsername());
        replysBeanList.get(position).getComments().add(commentItem);
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(mEditTextBodyLl != null && mEditTextBodyLl.getVisibility() == View.VISIBLE){
                updateEditTextBodyVisible(View.GONE, -1);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IssuedHelper.getInstance(this).onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
